package br.com.as.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.as.dominio.Produto;
import br.com.as.dominio.Troca;
import br.com.as.utils.HibernateUtility;

/**
 * Classe para consistencia de troca
 * 
 * @author msante
 *
 */
public class TrocaDAO {

	@SuppressWarnings("unchecked")
	public  List<Troca> listar() throws Exception{
		List<Troca> lista = null;
		Session sessao = HibernateUtility.getSession();
		try {
			Query query = sessao.createQuery(" from Troca ");		
			lista = query.list();			
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
		return lista;
	}

	public  void incluir(Troca troca) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();			
			sessao.saveOrUpdate(troca);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Troca> consultar(Produto produto) throws Exception{
		Session sessao = HibernateUtility.getSession();
		try {
			Query query = sessao.createQuery("from Troca cli where cli.produtoDefeito.id =:id or cli.produtoNovo.id =:id ");
			query.setLong("id", produto.getId());
			return query.list();			
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
	}
	
	public void excluir(Troca troca) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.delete(troca);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public  void alterar(Troca troca) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.update(troca);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public Troca pesquisarPorId(Long id) throws Exception{
		Session sessao = HibernateUtility.getSession();
		try {
			Troca temp = (Troca) sessao.get(Troca.class, id);
			return temp;
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
	}

}
